package kgame5.kio {
import kgame5.kutil.KEvent;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;

/**
 * @author kangkai
 * 这个是负责读取mapwin生成的地图文件用的
 * 如
 *  1_map[10][10] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
 * 
 * 1, 1, 0, 0, 0, 2, 0, 0, 0, 1, 1,
1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1,
1, 1, 0, 0, 0, 2, 0, 0, 0, 1, 1
 */
public class MapwinReader extends EventDispatcher {
	public static const 
		EVENTTYPE_OK : String = "EVENTTYPE_OK",
		EVENTTYPE_FAIL : String = "EVENTTYPE_FAIL";

	private var urlLoader : URLLoader;
	
	public var a2Data:Array;
	
	public function MapwinReader() {
		
	}

	public function Load(sUrl : String) {
		urlLoader = new URLLoader();
		urlLoader.addEventListener(Event.COMPLETE, onOK);
		urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onFail);
		urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onFail);
		
		urlLoader.load(new URLRequest(sUrl));
	}

	private function onOK(e : Event) {
		readData(urlLoader.data);
		this.dispatchEvent(new KEvent(EVENTTYPE_OK));
	}

	private function onFail(e : Event) {
		this.dispatchEvent(new KEvent(EVENTTYPE_FAIL));
	}

	//由加载到的text解析出一个2维度的数组

	public function readData(sText : String) {
		a2Data= new Array();
//		var a : Array = sText.split(String.fromCharCode(13, 10));
//		//trace(a.length);
//		for(var i : int = 1;i < a.length - 3;i++) {
//			var ss : String = a[i];
//			ss = ss.substr(1, ss.length - 3);
//			//trace(ss);
//			var aRow : Array = new Array();
//			var aa : Array = ss.split(",");
//			for(var k : int = 0;k < aa.length;k++) {
//				//trace(aa[k]);
//				aRow.push(int(aa[k]));
//			}
//			a2BarData.push(aRow);
//		}
		
		var a:Array=sText.split(String.fromCharCode(13,10));
		
		for each(var s:String in a){
			//这个是用来去掉最后一句的逗号
			if(s.lastIndexOf(",")==(s.length-1)){
				//trace(s.lastIndexOf(","),s.length-1);
				s=s.substr(0,s.length-1);
			}
			var aRow : Array = new Array();
			var aa : Array = s.split(",");
			for each(var k:String in aa) {
				aRow.push(int(k));
			}
			a2Data.push(aRow);
		}
	}
}//end of class
}
